<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Data extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 用户类型判断
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载类库
        $this->load->model('classesModel');
        $this->load->model('dataModel');
    }

    // 基础设置
	public function student_sign_today() {
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "data". DIRECTORY_SEPARATOR. "student_sign");
	}
    // 获取考勤数据的班级列表
    public function get_sign_class_list(){
        // 教师权限只能发布任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classId'] = $data['classId'] = $this->rmxUser['class_ids'];
        }
        // 班级id筛选
        if($this->get("gradeId")) $totalParams['gradeId'] = $data['gradeId'] = $this->get("gradeId");
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->classesModel->get_class_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($data);
        foreach($classList as &$class) {
            $class['className'] = $class['class_name'];
        }
        // 返回值
        exit(admin_table_data($total, $classList));   
    }

    // 查看考勤记录
    public function sign_data($classId){
        $this->date = $date = $this->get("date") ? $this->get("date") : date("Y-m-d");
        $this->classInfo = $classInfo = $this->classesModel->get_class_info($classId);
        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $this->rmxSchool['id'];
        $schduleParams['campusId'] = $this->campusInfo['id'];
        $schduleParams['isThisWeek'] = 1;
        // 兼容不同年级作息
        $schduleParams['gradeId'] = $classInfo['grade_id'];
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        // 获取考勤数据
        if($classInfo['class_type'] == CLASSES_TYPE_TEACHING) {
            // 走班
            // 获取当天走班所有课程
            // 获取本周指定课程信息
            $weekIndex = date("w",time());
            $weekIndex = $weekIndex ? $weekIndex : 7;       // 如果是0的话，就是周日，需要替换成7
            $teachingCourseArr = $this->classesModel->get_school_schedule_lesson(array('classId' => $classId, 'weekIndex' => $weekIndex));
            // 之前日期的考勤按最后一节情况
            $refreshClassIndex = $this->dataModel->get_refresh_class_index_for_teaching($timeArr, $this->date);
            if(empty($teachingCourseArr)) {
                // 当天没走班课程，默认都没签到
                $courseId = -1;
            } else {
                $courseId = -1;
                foreach($teachingCourseArr as $teachingCourse) {
                    if($teachingCourse['schedule_class_index'] <= $refreshClassIndex) {
                        $courseId = $teachingCourse['id'];
                    }
                }
            }
            // 获取当前走班课程数据
            $signData = $this->dataModel->get_sign_data($classInfo, $date, true, $courseId);
            foreach($signData as &$item) {
                if($item['sign_id']) {
                    if($item['state'] == SIGN_STATE_LEAVE) {
                        // 离校
                        $item['sign_id'] = 0;
                    }
                }
            }
            // echo'<pre>';var_export($signData);exit;
        } else {
            // 行政班
            $signData = $this->dataModel->get_sign_data($classInfo, $date);
            // 之前日期的考勤按最后一节情况
            $refreshClassIndex = $this->dataModel->get_refresh_class_index($timeArr, $this->date);
            foreach($signData as &$item) {
                if($item['sign_id']) {
                    if($item['state'] == SIGN_STATE_LEAVE) {
                        // 离校
                        $item['sign_id'] = 0;
                    } else {
                        // var_export($classIndex);exit;
                        if($item['schedule_class_index'] < $refreshClassIndex) {
                            // 重新签到后还没签
                            $item['sign_id'] = 0;
                        }
                    }
                }
            }
        }

        $signCount = 0;
        $notSignCount = 0;
        foreach($signData as $key => $item2) {
            if($item2['sign_id']) {
                $signCount ++;
            } else {
                $notSignCount ++;
            }

            // 处理温度
            $signData[$key]['temperature'] = handle_temperature($signData[$key]['temperature']);
        }
        $this->signData = $signData;
        $this->signCount = $signCount;
        $this->notSignCount = $notSignCount;
        // echo'<pre>';var_export($this->signData);exit;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "data". DIRECTORY_SEPARATOR. "sign_data");
    }

    // 查看考勤记录(旧版逻辑，只判断当天)
    public function sign_data_old($classId){
        $this->date = $date = $this->get("date") ? $this->get("date") : date("Y-m-d");
        $this->classInfo = $classInfo = $this->classesModel->get_class_info($classId);

        // 获取考勤数据
        $this->signData = $this->dataModel->get_sign_data($classInfo, $date);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "data". DIRECTORY_SEPARATOR. "sign_data");
    }

    public function student_sign() {
        $this->load->model('aioModel');
        $this->load->model('schoolModel');
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取年级对应的行政班级列表
        // $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeNormalClassList = json_encode($classArray);

        // 获取行政班
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $this->normalClassList = $this->classesModel->get_class_list($classParams);

        // 学校是否开启测温
        $this->temperatureOpen = false;
        $faceDetect = $this->rmxSchool['school_face_detect'];
        if($faceDetect == FACE_DETECT_TEMPERATURE || $faceDetect == FACE_DETECT_TEMPERATURE_HEAD || $faceDetect == FACE_DETECT_TEMPERATURE_WRIST) {
            $this->temperatureOpen = true;
        }

        // 是否开启一体机
        $this->aioOpen = false;
        $aioParams['schoolId'] = $this->rmxSchool['id'];
        $aioParams['campusId'] = $this->campusInfo['id'];
        $aioParams['isDelete'] = 0;
        $aioList = $this->aioModel->get_aio_list($aioParams);
        if($aioList) {
            $this->aioOpen = true;
            // 开启了测温一体机，即是开启了测温
            $this->temperatureOpen = true;
        }

        // 是否闸机
        $this->gateOpen = false;
        $gateParams['schoolId'] = $this->rmxSchool['id'];
        $gateParams['campusId'] = $this->campusInfo['id'];
        $gateParams['isDelete'] = 0;
        $gateList = $this->schoolModel->get_gate_list($gateParams);
        if($gateList) {
            $this->gateOpen = true;
        }

        // 生成又拍云签名,用于导入
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "data". DIRECTORY_SEPARATOR. "school_student_sign");
    }

    public function get_student_sign_list() {
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));

        if(trim($this->get("type"))) $totalParams['type'] = $data['type'] = trim($this->get("type"));
        if(trim($this->get("state"))) $totalParams['state'] = $data['state'] = trim($this->get("state"));
        // 筛选体温异常
        if(trim($this->get("temperature"))) $totalParams['temperature'] = $data['temperature'] = trim($this->get("temperature"));

        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $totalParams['classSet'] = $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId")) $totalParams['classId'] = $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        // 签到时间区间
        // if($this->get("begindate")) $totalParams['begindate'] = $data['begindate'] = $this->get("begindate") ? $this->get("begindate") : 0;
        // if($this->get("enddate")) $totalParams['enddate'] = $data['enddate'] = $this->get("enddate") ? $this->get("enddate") : 0;
        if($this->get("begintime")) $totalParams['begintime'] = $data['begintime'] = $this->get("begintime") ? $this->get("begintime") . ':00' : 0;
        if($this->get("endtime")) $totalParams['endtime'] = $data['endtime'] = $this->get("endtime") ? $this->get("endtime") . ':59' : 0;

        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classSet'] = $data['classSet'] = $this->rmxUser['class_ids'];
        }

        $total = $this->dataModel->get_student_sign_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        // $data['orderBy'] = '`id` DESC';
        $signList = $this->dataModel->get_student_sign_list($data);
        // echo '<pre>';var_export($signList);exit;
        // 获取学生其他信息
        foreach($signList as &$sign) {
            if($sign['sign_type'] == SIGN_TYPE_GATE) {
                // 闸机考勤
                // 第几节设为0
                $sign['schedule_class_index'] = 0;
            }

            // 星期几
            if($sign['schedule_week_index'] ) {
                $sign['schedule_week_index'] = $this->_transform_schedule_lesson_week_index($sign['schedule_week_index']);
            } else {
                $sign['schedule_week_index'] = date_to_week_format_new($sign['sign_date']);
            }        

            // 签到类型
            $sign['sign_type'] = transform_sign_type($sign['sign_type']);
            // 签到状态
            $sign['state'] = transform_sign_state($sign['state']);

            if($sign['schedule_class_index'] === NULL) {
                $sign['schedule_class_index'] = 0; 
            }

            // 处理温度
            $sign['temperature'] = handle_temperature($sign['temperature']);
        }

        // foreach($signList as &$sign) {
        //     if($sign['sign_type'] == SIGN_TYPE_GATE) {
        //         // 闸机考勤
        //         // 星期几
        //         $sign['schedule_week_index'] = date_to_week_format_new($sign['sign_date']);
        //         // 第几节设为0
        //         $sign['schedule_class_index'] = 0;
        //     } else {
        //         // 星期几
        //         $sign['schedule_week_index'] = $this->_transform_schedule_lesson_week_index($sign['schedule_week_index']);
        //     }
        //     // 签到类型
        //     $sign['sign_type'] = transform_sign_type($sign['sign_type']);
        //     // 签到状态
        //     $sign['state'] = transform_sign_state($sign['state']);

        //     if($sign['schedule_class_index'] === NULL) {
        //         $sign['schedule_class_index'] = 0; 
        //     }
        // }

        if($signList) {
            // 获取班级列表
            $classParams['schoolId'] = $this->rmxSchool['id'];
            $classParams['campusId'] = $this->campusInfo['id'];
            //过滤软删除
            $classParams['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($classParams);
            // 使用id作为键值
            $classList = array_value_to_key($classList, 'id');
            foreach($signList as &$sign) {
                if(isset($classList[$sign['class_id']])) {
                    $sign['class_name'] = $classList[$sign['class_id']]['class_name'];
                } else {
                    $sign['class_name'] = '';
                }
            }
        }

        // 返回值
        exit(admin_table_data($total, $signList));
    }

    private function _transform_schedule_lesson_week_index($weekday) {
		switch($weekday){
			case 1:
				return '星期一';
			case 2:
				return '星期二';
			case 3:
				return '星期三';
			case 4:
				return '星期四';
			case 5:
				return '星期五';
			case 6:
				return '星期六';
			case 7:
				return '星期日';
			default:
				return '';
		}
    }

    // 导出学生签到数据
    public function export_student_sign() {
        $this->load->model('aioModel');
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $data['keyword'] = trim($this->get("keyword"));

        if(trim($this->get("type"))) $data['type'] = trim($this->get("type"));
        if(trim($this->get("state"))) $totalParams['state'] = $data['state'] = trim($this->get("state"));
        // 筛选体温异常
        if(trim($this->get("temperature"))) $totalParams['temperature'] = $data['temperature'] = trim($this->get("temperature"));
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId"))  $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        // 签到时间区间
        // if($this->get("begindate")) $data['begindate'] = $this->get("begindate") ? $this->get("begindate") : 0;
        // if($this->get("enddate")) $data['enddate'] = $this->get("enddate") ? $this->get("enddate") : 0;
        if($this->get("begintime")) $totalParams['begintime'] = $data['begintime'] = $this->get("begintime") ? $this->get("begintime") . ':00' : 0;
        if($this->get("endtime")) $totalParams['endtime'] = $data['endtime'] = $this->get("endtime") ? $this->get("endtime") . ':59' : 0;

        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $data['classSet'] = $this->rmxUser['class_ids'];
        }
        // 获取数据
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        // $data['orderBy'] = '`id` DESC';
        $signList = $this->dataModel->get_student_sign_list($data);
        $exportData = array();
        // 学校是否开启测温
        $temperatureOpen = false;
        $faceDetect = $this->rmxSchool['school_face_detect'];
        if($faceDetect == FACE_DETECT_TEMPERATURE || $faceDetect == FACE_DETECT_TEMPERATURE_HEAD || $faceDetect == FACE_DETECT_TEMPERATURE_WRIST) {
            $temperatureOpen = true;
        }
        if($temperatureOpen == false) {
            // 是否开启一体机
            $aioParams['schoolId'] = $this->rmxSchool['id'];
            $aioParams['campusId'] = $this->campusInfo['id'];
            $aioParams['isDelete'] = 0;
            $aioList = $this->aioModel->get_aio_list($aioParams);
            if($aioList) {
                // 开启了测温一体机，即是开启了测温
                $temperatureOpen = true;
            }
        }

        if($temperatureOpen) {
            $firstRow = array(
                '学生名称',
                '班级名称',
                '课程科目',
                '星期',
                '节数',
                '签到类型',
                "签到状态",
                '签到时间',
                '体温'
            );
        } else  {
            $firstRow = array(
                '学生名称',
                '班级名称',
                '课程科目',
                '星期',
                '节数',
                '签到类型',
                "签到状态",
                '签到时间'
            );
        }

         // 获取班级列表
         $classParams['schoolId'] = $this->rmxSchool['id'];
         $classParams['campusId'] = $this->campusInfo['id'];
         //过滤软删除
         $classParams['isDelete'] = 0;
         $classList = $this->classesModel->get_class_list($classParams);
         // 使用id作为键值
         $classList = array_value_to_key($classList, 'id');

        $exportData[] = $firstRow;
        // 获取学生其他信息
        foreach($signList as &$sign) {
            // 星期几
            $sign['schedule_week_index'] = $this->_transform_schedule_lesson_week_index($sign['schedule_week_index']);
            // 签到类型
            $sign['sign_type'] = transform_sign_type($sign['sign_type']);
            // 签到状态
            $sign['state'] = transform_sign_state($sign['state']);

            if(isset($classList[$sign['class_id']])) {
                $sign['class_name'] = $classList[$sign['class_id']]['class_name'];
            } else {
                $sign['class_name'] = '';
            }

            // 暂时显示具体温度
            // // 处理温度
            // $sign['temperature'] = handle_temperature($sign['temperature']);

            if($temperatureOpen) {
                $exportData[] = array(
                    $sign['realname'],
                    $sign['class_name'],
                    $sign['schedule_lesson'],
                    $sign['schedule_week_index'],
                    $sign['schedule_class_index'],
                    $sign['sign_type'],
                    $sign['state'],
                    $sign['createtime'],
                    $sign['temperature'] ? $sign['temperature'] : '无',
                );
            } else {
                $exportData[] = array(
                    $sign['realname'],
                    $sign['class_name'],
                    $sign['schedule_lesson'],
                    $sign['schedule_week_index'],
                    $sign['schedule_class_index'],
                    $sign['sign_type'],
                    $sign['state'],
                    $sign['createtime']
                );
            }

        }

        // var_export($signList);exit;
        $widthParams = array(
            array(
                'index' => 'B',
                'width' => 20
            ),
            array(
                'index' => 'C',
                'width' => 20
            ),
            array(
                'index' => 'D',
                'width' => 16
            ),
            array(
                'index' => 'E',
                'width' => 20
            ),
            array(
                'index' => 'F',
                'width' => 20
            ),
            array(
                'index' => 'G',
                'width' => 20
            ),
            array(
                'index' => 'H',
                'width' => 18
            )
        );
        exportExcel('考勤数据表', $exportData, $widthParams);
    }

    // 导出学生签到图片
    public function export_student_sign_img() {
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $data['keyword'] = trim($this->get("keyword"));

        if(trim($this->get("type"))) $data['type'] = trim($this->get("type"));
        if(trim($this->get("state"))) $totalParams['state'] = $data['state'] = trim($this->get("state"));
        // 筛选体温异常
        if(trim($this->get("temperature"))) $totalParams['temperature'] = $data['temperature'] = trim($this->get("temperature"));
        // 学生年级筛选
        if($this->get("gradeId")) {
            $params['gradeId'] = $this->get("gradeId");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $data['classSet'] = array_value_implode($classList, "id");
        }
        // 学生班级筛选
        if($this->get("classId"))  $data['classId'] = $this->get("classId") ? $this->get("classId") : 0;
        // 签到时间区间
        // if($this->get("begindate")) $data['begindate'] = $this->get("begindate") ? $this->get("begindate") : 0;
        // if($this->get("enddate")) $data['enddate'] = $this->get("enddate") ? $this->get("enddate") : 0;
        if($this->get("begintime")) $totalParams['begintime'] = $data['begintime'] = $this->get("begintime") ? $this->get("begintime") . ':00' : 0;
        if($this->get("endtime")) $totalParams['endtime'] = $data['endtime'] = $this->get("endtime") ? $this->get("endtime") . ':59' : 0;

        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $data['classSet'] = $this->rmxUser['class_ids'];
        }
        // 获取数据
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        // $data['orderBy'] = '`id` DESC';
        $signList = $this->dataModel->get_student_sign_list($data);
        
        $exportData = array();
        // 获取学生其他信息
        foreach($signList as $sign) {
            if($sign['sign_img']) {
                // $sign['realname'] =  $sign['realname'] . '_' . $sign['class_name'];

                if(isset($exportData[$sign['student_id']])) {
                    $key = $sign['student_id'] . '_2'; 
                    $name = $sign['realname'] . '_2'; 
                } else {
                    $key = $sign['student_id'];
                    $name = $sign['realname'];
                }
                $exportData[$key] = array(
                    'name' => $name,
                    'img' => $sign['sign_img']
                );
            }

        }

        $zipName = '';
        if($this->get("classId")) {
            $classInfo = $this->classesModel->get_class_info($this->get("classId"));
            if($classInfo && $classInfo['class_name']) {
                $zipName .= $classInfo['class_name'];
            }
        } else {
            if($this->get("gradeId")) {
                $gradeInfo = $this->classesModel->get_grade_info($this->get("gradeId"));
                if($gradeInfo && $gradeInfo['grade_name']) {
                    $zipName .= $gradeInfo['grade_name'];
                }
            }
        }
        $zipName = $zipName . date('Y-m-d-His') . '.zip'; // 压缩包文件名，不能包含中文
        $this->downloadZipImg($exportData, $zipName);
    }

    // 教师考勤数据页面
    public function teacher_sign() {
        $this->load->model('aioModel');
        $this->load->model('schoolModel');
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取年级对应的行政班级列表
        // $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeNormalClassList = json_encode($classArray);

        // 获取行政班
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $this->normalClassList = $this->classesModel->get_class_list($classParams);

        // 学校是否开启测温
        $this->temperatureOpen = false;
        $faceDetect = $this->rmxSchool['school_face_detect'];
        if($faceDetect == FACE_DETECT_TEMPERATURE || $faceDetect == FACE_DETECT_TEMPERATURE_HEAD || $faceDetect == FACE_DETECT_TEMPERATURE_WRIST) {
            $this->temperatureOpen = true;
        }

        // 是否开启一体机
        $this->aioOpen = false;
        $aioParams['schoolId'] = $this->rmxSchool['id'];
        $aioParams['campusId'] = $this->campusInfo['id'];
        $aioParams['isDelete'] = 0;
        $aioList = $this->aioModel->get_aio_list($aioParams);
        if($aioList) {
            $this->aioOpen = true;
            // 开启了测温一体机，即是开启了测温
            $this->temperatureOpen = true;
        }

        // 是否闸机
        $this->gateOpen = false;
        $gateParams['schoolId'] = $this->rmxSchool['id'];
        $gateParams['campusId'] = $this->campusInfo['id'];
        $gateParams['isDelete'] = 0;
        $gateList = $this->schoolModel->get_gate_list($gateParams);
        if($gateList) {
            $this->gateOpen = true;
        }

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "data". DIRECTORY_SEPARATOR. "school_teacher_sign");
    }

    public function get_teacher_sign_list() {
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));

        if(trim($this->get("type"))) $totalParams['type'] = $data['type'] = trim($this->get("type"));
        if(trim($this->get("state"))) $totalParams['state'] = $data['state'] = trim($this->get("state"));
        // 筛选体温异常
        if(trim($this->get("temperature"))) $totalParams['temperature'] = $data['temperature'] = trim($this->get("temperature"));

        
        // 签到时间区间
        if($this->get("begintime")) $totalParams['begintime'] = $data['begintime'] = $this->get("begintime") ? $this->get("begintime") . ':00' : 0;
        if($this->get("endtime")) $totalParams['endtime'] = $data['endtime'] = $this->get("endtime") ? $this->get("endtime") . ':59' : 0;

        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classSet'] = $data['classSet'] = $this->rmxUser['class_ids'];
        }

        $total = $this->dataModel->get_teacher_sign_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        // $data['orderBy'] = '`id` DESC';
        $signList = $this->dataModel->get_teacher_sign_list($data);
        // echo '<pre>';var_export($signList);exit;
        // 获取学生其他信息
        foreach($signList as &$sign) {
            if($sign['sign_type'] == SIGN_TYPE_GATE) {
                // 闸机考勤
                // 第几节设为0
                $sign['schedule_class_index'] = 0;
            }

            // 星期几
            if($sign['schedule_week_index'] ) {
                $sign['schedule_week_index'] = $this->_transform_schedule_lesson_week_index($sign['schedule_week_index']);
            } else {
                $sign['schedule_week_index'] = date_to_week_format_new($sign['sign_date']);
            }        

            // 签到类型
            $sign['sign_type'] = transform_sign_type($sign['sign_type']);
            // 签到状态
            $sign['state'] = transform_sign_state($sign['state']);

            if($sign['schedule_class_index'] === NULL) {
                $sign['schedule_class_index'] = 0; 
            }

            // 处理温度
            $sign['temperature'] = handle_temperature($sign['temperature']);
        }

        if($signList) {
            // 获取班级列表
            $classParams['schoolId'] = $this->rmxSchool['id'];
            $classParams['campusId'] = $this->campusInfo['id'];
            //过滤软删除
            $classParams['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($classParams);
            // 使用id作为键值
            $classList = array_value_to_key($classList, 'id');
            foreach($signList as &$sign) {
                if(isset($classList[$sign['class_id']])) {
                    $sign['class_name'] = $classList[$sign['class_id']]['class_name'];
                } else {
                    $sign['class_name'] = '';
                }
            }
        }

        // 返回值
        exit(admin_table_data($total, $signList));
    }

    /**
     * 下载图片并生成压缩包
     * @param $data    图片数组，一维
     * @param $tmpDir 存放路径
     * @return string
     */
    private function downloadZipImg($picAllArr, $zipName)
    {
        // $picAllArr = ['https://resource.rongmixiao.com/2020/10/13/16025683315485.jpeg2','https://resource.rongmixiao.com/2020/10/14/oqxgw4cbplf32q461bh5tuobwmvfrcci.jpg'];
        // $tmpDir = '这里是图片下载路径目录'; // 类似于/www/public/upload/
        $tmpDir = defined('SAE_TMP_PATH') ? SAE_TMP_PATH : '/';
        if (!file_exists($tmpDir)) {
            //创建文件夹
            mkdir($tmpDir, 0777, true);
        }

        $zipNameUrl = $tmpDir . $zipName; // 文件路径

        // 生成文件
        $zip = new \ZipArchive();
        if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
            //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
            if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
                // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
                return  '下载失败，文件夹不存在';
            }
        }

        // window下必须转码，linux不可以转码，所以判断环境
        if(!defined('SAE_TMP_PATH')) {
            $zipNameUrl = iconv("utf-8", "gbk//IGNORE", $zipNameUrl);
        }

        foreach ($picAllArr as $fileArr) {
            $file = $fileArr['img'];
            //判断图片是否存在
            $isFile = $this->checkFileExists($file);
            if (!$isFile) {
                continue;
            }
            //抓取图片内容
            $fileContent = file_get_contents($file);     
            $fileName = $fileArr['name'] . '.jpg';
            //添加图片
            $zip->addFromString($fileName, $fileContent);
        }
        // 关闭
        $zip->close();

        //没有文件
        if (!file_exists($zipNameUrl)) {
            return '下载失败，图片不存在或无法下载';
        }
        // var_export($fileContent);exit; 
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . $zipName); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: ' . filesize($zipNameUrl)); //告诉浏览器，文件大小

        // 下面2步必须要
        // ob_clean();  // linux加这步压缩包打不开
        flush();

        @readfile($zipNameUrl);
        unlink($zipNameUrl); // 删除文件
        exit;
    }
    /**
     * 判断文件是否存在，支持本地及远程文件
     * @param String $file 文件路径
     * @return Boolean
     */
    private function checkFileExists($file)
    {
        // 远程文件
        if (strtolower(substr($file, 0, 5)) == 'https') {
            // 远程文件
            $header = get_headers($file, true);
            return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));

        } elseif (strtolower(substr($file, 0, 4)) == 'http') {
            // 远程文件
            $header = get_headers($file, true);
            return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
        } else {
            // 本地文件
            return file_exists($file);
        }
    }

    // 食谱管理页面
    public function recipe() {
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "data". DIRECTORY_SEPARATOR. "recipe");
    }

    // 获取食谱列表
    public function get_recipe_list() {
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;

        $total = $this->dataModel->get_recipe_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        // $data['orderBy'] = '`id` DESC';
        $recipeList = $this->dataModel->get_recipe_list($data);

        if($recipeList) {
            foreach($recipeList as &$recipe) {
                // 查询发布班级
                $params['classId'] = $recipe['class_id'];
                // 过滤软删除
                $params['isDelete'] = 0;
                $recipe['classList'] = $this->classesModel->get_grade_class_list($params);
                // 获取所有菜品分类
                $cateParams['schoolId'] = $this->rmxSchool['id'];
                $cateParams['campusId'] = $this->campusInfo['id'];
                $cateParams['isDelete'] = 0;
                $cateList = $this->dataModel->get_recipe_cate_list($cateParams);
                $cateList = array_value_to_key($cateList, 'id');
                // 查询菜品分类
                $cateArr = explode(',', $recipe['cate']);
                $cateTitleArr = array();
                foreach($cateArr as $cateId) {
                    if(isset($cateList[$cateId])) {
                        array_push($cateTitleArr, $cateList[$cateId]['title']);
                    }
                }
                $recipe['cateTitleArr'] = $cateTitleArr;
                // 获取菜品时段
                $timeArrTemp = json_decode($recipe['time_json'], true);
                $timeArr = array();
                foreach($timeArrTemp as $time) {
                    $timeStr = $time['begin_time'] . ' - ' . $time['end_time'];
                    array_push($timeArr, $timeStr);
                }
                $recipe['timeArr'] = $timeArr;
            }
        }
        // echo '<pre>';var_export($recipeList);exit;
        // 返回值
        exit(admin_table_data($total, $recipeList));
    }

    // 修改食谱页面
    public function save_recipe($recipeId = 0) {
        if($recipeId) {
            $this->recipeId = $recipeId;
            $recipe = $this->dataModel->get_recipe_info($recipeId);
            $recipe['timeArr'] = json_decode($recipe['time_json'], true);
            $this->recipe = $recipe;
        }
        // 获取菜品分类列表
        $cateParams['schoolId'] = $this->rmxSchool['id'];
        $cateParams['campusId'] = $this->campusInfo['id'];
        $cateParams['isDelete'] = 0;
        $this->cateList = $this->dataModel->get_recipe_cate_list($cateParams);

        // 年级班级列表
        $params['isDelete'] = 0;
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getLevelData'] = true;
        // 只获取行政班
        $params['classType'] = CLASSES_TYPE_NORMAL;
        $this->gradeArray = $this->classesModel->get_grade_class_list($params);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "data". DIRECTORY_SEPARATOR. "save_recipe");
    }

    // 保存食谱操作
    public function save_recipe_action(){
        $id = $this->post('id');
        $title = $this->post('title');
        $scheduleDataArr = $this->post('time_arr');
        $recipeClass = $this->post("recipe_class");
        $cate = $this->post("cate");
        // echo '<pre>';var_export($cate);exit;
        if(!$cate) throw new Exception("请选择菜品分类");
        if(!$recipeClass) throw new Exception("请选择发布班级");
        if(empty($scheduleDataArr)) {
            throw new Exception('菜品时段不能为空');
        }
        foreach($scheduleDataArr as $key => $scheduleData) {
            $timeslot = $key + 1;
            if($scheduleData['begin_time'] == $scheduleData['end_time']) {
                throw new Exception('第' . $timeslot . '节：开始时间等于结束时间');
            }
            if($scheduleData['begin_time'] > $scheduleData['end_time']) {
                throw new Exception('第' . $timeslot . '节：开始时间大于结束时间');
            }
            if($timeslot != count($scheduleDataArr)) {
                if($scheduleDataArr[$key + 1]['begin_time'] < $scheduleData['end_time']) {
                    $nextTimeslot = $key + 2;
                    throw new Exception('第' . $nextTimeslot . '节：开始时间不能比上一节时间小');
                }
            }
        }
        // 计算下午节数
        $timeJson = json_encode($scheduleDataArr, JSON_UNESCAPED_UNICODE);
        $data = array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_id' => $this->rmxUser['id'],
            'class_id' => $recipeClass,
            'cate' => implode(',', $cate),
            'title' => $title,
            'time_json' => $timeJson,
            'updatetime' => date('Y-m-d H:i:s')
        );

        if(empty($id)) {
            // 新增
            $this->db->insert(DataModel::$recipeTable, array_merge($data, array('createtime' => date('Y-m-d H:i:s'))));
            $msg = '添加成功';
        } else {
            // 更新
            $this->db->where('id', $id);
            $this->db->update(DataModel::$recipeTable, $data);
            $msg = '修改成功';
        }
        exit(json($msg, true));
    }
    // 删除食谱
    public function delete_recipe_action() {
        $id = $this->post('id');
        // 获取菜品分类详情
        $recipeInfo = $this->dataModel->get_recipe_info($id);
        if(empty($recipeInfo)) {
            throw new Exception('id不存在');
        }
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(DataModel::$recipeTable, $data, array('id' => $id));

        exit(json('删除成功', true));
    }
    // 菜品分类页面
    public function recipe_cate() {
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "data". DIRECTORY_SEPARATOR. "recipe_cate");
    }

    public function save_recipe_cate_action(){
        $roomId = $this->post("id");
        $title = trim($this->post("title"));
        // 数据检查
        if(!$title) throw new Exception("请填写菜品分类名称");
        // 检查本校是否有重复菜品分类
        if($this->dataModel->check_recipe_cate_title_exists($this->rmxSchool['id'], $title, $roomId)) {
            throw new Exception("菜品分类名称已存在");
        }
        // 入库
        $data['campus_id'] = $this->campusInfo['id'];
        $data['title'] = $title;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($roomId) {
            $this->db->update(DataModel::$recipeCateTable, $data,"id='{$roomId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(DataModel::$recipeCateTable, $data);
        }
        $msg = $roomId ? '修改菜品分类成功' : '添加菜品分类成功';
        exit(json($msg, true));
    }
    // 获取菜品分类列表
    public function get_recipe_cate_list(){
        // 筛选
        if($this->get("keyword")) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));

        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->dataModel->get_recipe_cate_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $list = $this->dataModel->get_recipe_cate_list($data);
        // 返回值
        exit(admin_table_data($total, $list));
    }
    // 删除菜品分类
    public function delete_recipe_cate_action() {
        $id = $this->post('id');
        // 获取菜品分类详情
        $recipeCateInfo = $this->dataModel->get_recipe_cate_info($id);
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(DataModel::$recipeCateTable, $data, array('id' => $id));

        exit(json('删除成功', true));
    }

    // 食谱详情页面
    public function recipe_detail($recipeId) {
        // 获取食谱详情
        $this->recipeId = $recipeId;
        $recipe = $this->dataModel->get_recipe_info($recipeId);
        $recipe['timeArr'] = json_decode($recipe['time_json'], true);
        $this->recipe = $recipe;
        // 获取全校菜品分类列表
        $cateParams['schoolId'] = $this->rmxSchool['id'];
        $cateParams['campusId'] = $this->campusInfo['id'];
        $cateParams['isDelete'] = 0;
        $schoolCateList = $this->dataModel->get_recipe_cate_list($cateParams);
        $schoolCateList = array_value_to_key($schoolCateList, 'id');
        // 获取食谱下的菜品分类列表
        $cateIdArr = explode(',', $recipe['cate']);
        $recipeCateList = array();
        foreach($cateIdArr as $cateId) {
            if(isset($schoolCateList[$cateId])) {
                $arr = array(
                    'id' => $cateId,
                    'title' => $schoolCateList[$cateId]['title']
                );
                array_push($recipeCateList, $arr);
            }
        }
        $this->recipeCateList = $recipeCateList;
        // 获取食谱详情列表
        $detailParams['schoolId'] = $this->rmxSchool['id'];
        $detailParams['campusId'] = $this->campusInfo['id'];
        $detailParams['recipeId'] = $recipeId;
        $detailParams['isDelete'] = 0;
        $detailList = $this->dataModel->get_recipe_detail_list($detailParams);
        foreach($detailList as &$detail) {
            // 转换菜品内容为数组
            $detail['contentArr'] = json_decode($detail['content'], true);
        }
        $this->detailList = $detailList;
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
    //    echo '<pre>';var_export($detailList);exit;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "data". DIRECTORY_SEPARATOR. "recipe_detail");
    }

    // 保存食谱详情操作
    public function save_recipe_detail_action(){
        $detailId = $this->post('detail_id');
        // 菜品排序值
        $postKey = $this->post('key');
        $recipeId = $this->post('recipe_id');
        $title = trim($this->post('title'));
        $price = $this->post('price');
        $cateId = $this->post("cate_id");
        $img = $this->post('img') ? $this->post('img') : '';
        if(strstr($img, 'images/upload.png')) {
            $img = '';
        }
        $weekIndex = $this->post('week_index');
        $classIndex = $this->post('class_index');
        if(!$title) throw new Exception("请填写菜品名称");
        if(!$price) throw new Exception("请填写菜品价格");
        if(!$cateId) throw new Exception("请选择菜品分类");

        $recipeContentArr = array();
        // 菜品
        $contentArr = array(
            'title' => $title,
            'price' => $price,
            'cate_id' => $cateId,
            'img' => $img,
        );

            // var_export($postKey);exit;
        if($detailId) {
            // 更新操作
            // 获取食谱详情
            $recipeDetailInfo = $this->dataModel->get_recipe_detail_info($detailId);
            $recipeContentArr = json_decode($recipeDetailInfo['content'], true);
            // 若key为-1，即为添加
            if($postKey == '-1' || $postKey == '') {
                // 插入
                array_push($recipeContentArr, $contentArr);
            } else {
                // 修改
                foreach($recipeContentArr as $key => $item) {
                    if($key == $postKey) {
                        $recipeContentArr[$key] = $contentArr;
                    }
                }
            }
            // var_export($recipeDetailInfo);exit;
        } else {
            // 插入操作
            array_push($recipeContentArr, $contentArr);
        }
            // echo'<pre>';var_export($recipeContentArr);exit;
        $recipeContentStr = json_encode($recipeContentArr, JSON_UNESCAPED_UNICODE);
        $data = array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'recipe_id' => $recipeId,
            'week' => $weekIndex,
            'timeslot' => $classIndex,
            'content' => $recipeContentStr,
            'is_delete' => 0,
            'updatetime' => date('Y-m-d H:i:s')
        );

        if(empty($detailId)) {
            // 新增
            $this->db->insert(DataModel::$recipeDetailTable, array_merge($data, array('createtime' => date('Y-m-d H:i:s'))));
            $msg = '添加成功';
        } else {
            // 更新
            $this->db->where('id', $detailId);
            $this->db->update(DataModel::$recipeDetailTable, $data);
            $msg = '修改成功';
        }
        exit(json($msg, true));
    }

    // 删除食谱详情操作
    public function delete_recipe_detail_action(){
        $id = $this->post('detail_id');
        // 菜品排序值
        $postKey = $this->post('key');
        // 获取菜品详情
        $recipeDetailInfo = $this->dataModel->get_recipe_detail_info($id);
        $recipeContentArr = json_decode($recipeDetailInfo['content'], true);
        // 删除该项菜品
        unset($recipeContentArr[$postKey]);
        $recipeContentJson = json_encode($recipeContentArr, JSON_UNESCAPED_UNICODE);
        $data = array(
            'content' => $recipeContentJson,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(DataModel::$recipeDetailTable, $data, array('id' => $id));

        exit(json('删除成功', true));
    }
}